﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PalBattleEmulator.Command;

namespace PalBattleEmulator.Graphic
{
    /// <summary>
    /// UnitGraphicControl.xaml 的交互逻辑
    /// </summary>
    public abstract partial class UnitGraphic : UserControl, IGraphicElement
    {
        protected const int ZINDEX_NORMAL = 0;
        protected const int ZINDEX_ACTIVE = 0;

        protected List<BitmapSource> sources;
        protected UnitGraphicState graphicState;
        protected Queue<GraphicFrame> actionFrames;

        public UnitGraphic()
        {
            InitializeComponent();
            actionFrames = new Queue<GraphicFrame>();
        }

        public void Draw()
        {
            //如果有动态帧，优先绘制
            if (actionFrames.Count > 0)
            {
                GraphicFrame frame = actionFrames.Peek();
                this.Dispatcher.Invoke(new drawFrameDelegate(drawFrame), System.Windows.Threading.DispatcherPriority.Normal, new object[] { frame });
                frame.Delay++;
                if (frame.Delay < frame.RepeatTimes) return;
                actionFrames.Dequeue();
                
                //finish
                
            }
            //否则循环绘制静态帧
            else
            {
                GraphicFrame frame = GetIdleFrame();
                this.Dispatcher.Invoke(new drawFrameDelegate(drawFrame), System.Windows.Threading.DispatcherPriority.Normal, new object[] { frame });
                frame.Delay++;
                if (frame.Delay < frame.RepeatTimes) return;
            }
            
            
        }

        public abstract GraphicFrame GetIdleFrame();

        public abstract void OnCommand(GameCommand command);

        private delegate void drawFrameDelegate(GraphicFrame frame);

        private void drawFrame(GraphicFrame frame)
        {
            this.BeginInit();
            if (frame.FrameIndex < 0 || frame.FrameIndex >= sources.Count) return;
            BitmapSource source = sources[frame.FrameIndex];

            if (image.ImageSource != source)
            {
                image.ImageSource = source;
                this.Width = source.PixelWidth;
                this.Height = source.PixelHeight;
            }

            Canvas.SetLeft(this, frame.PosX - source.PixelWidth / 2);
            Canvas.SetTop(this, frame.PoxY - source.PixelHeight);
            Canvas.SetZIndex(this, frame.ZIndex);
            this.EndInit();
        }
    }

    public enum UnitGraphicState
    {
        Idle,
        Action,
    }
}
